using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;
using IAS.MacroRenderings.Interfaces;
namespace IAS.MacroRenderings.Data
{
    /// <summary>
    /// 
    /// </summary>
    public class DataXML : DataBase, IDropDownListDataProvider
    {

        private const string xmlFolder = "/data/MacroRenderings/xml/";
        private const string extension = ".xml";

        #region IDropDownListDataProvider Members

        public Dictionary<string, string> GetData()
        {
            string xmlFile = HttpContext.Current.Server.MapPath(xmlFolder + className + extension);            
            Dictionary<string, string> dt = new Dictionary<string, string>();
            try
            {
                XmlDocument xd = new XmlDocument();
                xd.Load(xmlFile);
                dt = convertXMLToDictionary(xd);
            }
            catch (Exception ex) {
                this.LogErrorToUmbraco(ex.Message.ToString() + " processing xml file " + xmlFile);
            }
            return dt;
            
        }


        #endregion

        #region IDropDownListDataProvider Members


        public string ClassName
        {
            set { this.className = value; }
        }

        #endregion

        #region internal
        private Dictionary<string, string> convertXMLToDictionary(XmlDocument xd)
        {
            Dictionary<string, string> dt = new Dictionary<string, string>();
            XmlNodeList xn = xd.SelectNodes("/Items/Item");
            foreach (XmlNode n in xn)
            {
                dt.Add(n.Attributes.GetNamedItem("key").Value, n.Attributes.GetNamedItem("value").Value);
            }
            return dt;
        }

        /// <summary>
        /// usign for testing
        /// </summary>
        /// <param name="xd"></param>
        /// <returns></returns>
        public Dictionary<string, string> ConvertXMLToDictionary(XmlDocument xd)
        {
            return convertXMLToDictionary(xd);
        }
        #endregion
    }
}
